﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UBlockly.Compotent;
using UBlockly.Scriptable;
using UnityEngine.UI;

namespace UBlockly.UI
{
    public abstract class BlockObject : MonoBehaviour
    {
        [SerializeField]
        private PackerObject packer;
        [SerializeField]
        private NSlotPair slotPair;
        
        internal BlockEventHandler EventHandler;
        public LinkedListNode<Node> Node { get; private set; }
        public Vector3 Position => transform.position;
        public Vector3 LocalPosition => transform.localPosition;
        public Transform Parent => transform.parent;
        public BlockType BlockType { get; private set; }
        public RectTransform RectTransform;
 
        protected virtual void Awake()
        {
            RectTransform = GetComponent<RectTransform>();
            EventHandler = gameObject.AddCompontentIfNoExist<BlockEventHandler>();
        }

        public void BindNode(Node node)
        {
            Node = new LinkedListNode<Node>(node);
            BlockType = node.Scriptable.ResultType == ILVarType.VoidR ? BlockType.SlotType : BlockType.PackType;
            if (BlockType == BlockType.SlotType)
            {
                ULinkedList<Node> list = new ULinkedList<Node>();
                list.MuteNotify();
                list.AddFirst(Node);
                list.OpenNoify();
            }
            packer?.DoInit(node);
        }

        internal void SetPacker(PackerObject packer)
        {
            this.packer = packer;
        }

        internal void SetSlot(NSlotPair pair)
        {
            this.slotPair = pair;
        }

        public void AttacthToBlock(BlockAnchor parentBlock)
        {
            transform.SetParent(parentBlock.transform);
            transform.localPosition += new Vector3(0, 0, 1);
        }

        public void UnAttach(Transform parent)
        {
            transform.SetParent(parent);
            transform.localPosition -= new Vector3(0, 0, 1);
        }
        public virtual void ReSize()
        {
            GetComponent<IUAnchor>().Resize();
        }

        public Vector2 GetSize()
        {
            return GetComponent<IUAnchor>().GetSize();
        }

        internal void OnBodyChanged()
        {
            Node.Value.BodyChangeNotify();
        }

        public void SetPosition(Vector3 pos)
        {
            transform.position = pos;
        }

        public Transform Find(string name)
        {
            return transform.Find(name);
        }

        internal PackerObject GetPackerObject()
        {
            return packer;
        }

        internal NSlotPair GetSlotPair()
        {
            return slotPair;
        }
    }
}
